<template>
  <el-drawer
    :title="$t('modules.data_center.dynamic_chart.title')"
    v-bind='$attrs'
    v-on='$listeners'
    @closed='handleClose'
  >
    <div class='chart-drawer'>
      <!-- <div>图表类型</div> -->
      <div class='chart-icons'>
        <el-tooltip v-show='activeIndex === 1' :content="$t('modules.data_center.dynamic_chart.chart_list.bar')">
          <img
            :src='icons.barActive'
            class='selected'
            alt='chart-bar'
          ></img>
        </el-tooltip>
        <el-tooltip v-show='activeIndex !== 1' :content="$t('modules.data_center.dynamic_chart.chart_list.bar')">
          <img
            :src='icons.bar'
            alt='chart-bar'
            @click='() => selectChart(1)'
          ></img>
        </el-tooltip>

        <el-tooltip v-show='activeIndex === 2' :content="$t('modules.data_center.dynamic_chart.chart_list.line')">
          <img
            :src='icons.lineActive'
            class='selected'
            alt='chart-bar'
          ></img>
        </el-tooltip>
        <el-tooltip v-show='activeIndex !== 2' :content="$t('modules.data_center.dynamic_chart.chart_list.line')">
          <img
            :src='icons.line'
            alt='chart-bar'
            @click='() => selectChart(2)'
          ></img>
        </el-tooltip>

        <el-tooltip v-show='activeIndex === 3' :content="$t('modules.data_center.dynamic_chart.chart_list.pie')">
          <img
            :src='icons.pieActive'
            class='selected'
            alt='chart-bar'
          />
        </el-tooltip>

        <el-tooltip v-show='activeIndex !== 3' :content="$t('modules.data_center.dynamic_chart.chart_list.pie')">
          <img
            :src='icons.pie'
            alt='chart-bar'
            @click='() => selectChart(3)'
          />
        </el-tooltip>
        <el-tooltip v-show='activeIndex === 4' :content="$t('modules.data_center.dynamic_chart.chart_list.table')">
          <img
            :src='icons.tableActive'
            class='selected'
            alt='chart-bar'
          />
        </el-tooltip>

        <el-tooltip v-show='activeIndex !== 4' :content="$t('modules.data_center.dynamic_chart.chart_list.table')">
          <img
            :src='icons.table'
            alt='chart-bar'
            @click='() => selectChart(4)'
          />
        </el-tooltip>
      </div>
      <el-form :model='form' ref='form' label-position='top' :rules='rules' size='mini'
               :validate-on-rule-change='false'>
        <el-form-item :label="$t('modules.data_center.dynamic_chart.mode_name')" prop='modeName'>
          <el-input v-model='form.modeName' maxlength='50' show-word-limit
                    @blur='()=>form.modeName = form.modeName.trim()'></el-input>
        </el-form-item>

        <el-form-item
          :label="$t('modules.data_center.dynamic_chart.data_source')"
          prop='datasourceCode'
        >
          <el-select v-model='form.datasourceCode' @change='datasourceChange'>
            <el-option
              v-for='(item) in datasources'
              :value='item.datasourceCode'
              :key='item.datasourceCode'
              :label="$t('contract_plat.'+item.datasourceCode)"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          :label="$t('modules.data_center.dynamic_chart.x_axis')"
          prop='x'
          v-if='activeIndex === 1 || activeIndex === 2'
        >
          <el-select v-model='form.x' value-key='code'>
            <el-option
              v-for='item in _xAxisDatas'
              :key='item.code'
              :label="$t('modules.data_center.dynamic_chart.columns.'+item.code)"
              :value='item'
              :disabled='item.disabled'
            />
          </el-select>
        </el-form-item>

        <el-form-item
          :label="$t('modules.data_center.dynamic_chart.y_axis')"
          prop='y'
          v-if='activeIndex === 1 || activeIndex === 2 '
        >
          <el-select
            v-model='form.y'
            v-if="form.legend === ''"
            multiple
            key='multiple'
            value-key='code'
          >
            <el-option
              v-for='item in yAxisDatas'
              :key='item.code'
              :label="$t('modules.data_center.dynamic_chart.columns.'+item.code)"
              :value='item'
            />
          </el-select>

          <el-select
            v-model='form.y'
            key='single'
            v-else
            value-key='code'
          >
            <el-option
              v-for='item in yAxisDatas'
              :key='item.code'
              :label="$t('modules.data_center.dynamic_chart.columns.'+item.code)"
              :value='item'
            />
          </el-select>
        </el-form-item>

        <el-form-item
          :label="$t('modules.data_center.dynamic_chart.value')"
          prop='value'
          v-if='activeIndex == 3'
        >
          <el-select
            v-model='form.value'
            v-if="form.legend === ''"
            multiple
            key='multiple'
            value-key='code'
          >
            <el-option
              v-for='item in yAxisDatas'
              :key='item.code'
              :label="$t('modules.data_center.dynamic_chart.columns.'+item.code)"
              :value='item'
            />
          </el-select>
          <el-select
            v-model='form.value'
            key='single'
            v-else
            value-key='code'
          >
            <el-option
              v-for='item in yAxisDatas'
              :key='item.code'
              :label="$t('modules.data_center.dynamic_chart.columns.'+item.code)"
              :value='item'
            />
          </el-select>
        </el-form-item>

        <el-form-item
          :label="$t('modules.data_center.dynamic_chart.legend')"
          prop='legend'
          v-if='((activeIndex === 1  || activeIndex === 2) &&  ((!Array.isArray(form.y) || form.y.length <= 1))) || (activeIndex === 3 && (!Array.isArray(form.value) ||form.value.length <=1))'
        >
          <el-select v-model='form.legend' :loading='loading' value-key='code' @change='legendChangeHandle' clearable>
            <el-option
              v-for='item in _legendDatas'
              :key='item.code'
              :label="$t('modules.data_center.dynamic_chart.columns.'+item.code)"
              :value='item'
              :disabled='item.disabled'
            />
          </el-select>
        </el-form-item>

        <el-form-item
          :label="$t('modules.data_center.dynamic_chart.column')"
          prop='column'
          v-if='activeIndex === 4'
        >
          <el-select v-model='form.column' multiple value-key='code'>
            <el-option
              v-for='item in columnDatas'
              :key='item.code'
              :label="$t('modules.data_center.dynamic_chart.columns.'+item.code)"
              :value='item'
              :disabled='item.disabled'
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('modules.data_center.dynamic_chart.condition')">
          <el-select class='w-40' v-model='form.conditionType' clearable @change='conditionChangeHandle()'>
            <el-option :value='1' :label="$t('modules.data_center.dynamic_chart.conditionType.1')"></el-option>
          </el-select>
          <el-input @keypress.native='preventNonNumericalInput' type='number' v-model='form.conditionValue' :min='1'
                    :disabled="form.conditionType === ''" :max='99999' class='w-40'
                    oninput='if(value>99999)value=99999;if(value.length>5)value=value.slice(0,5);if(value<0)value=0'></el-input>
          <!--          <el-input :min='0'  :max='99999' v-model="form.conditionValue" type='number' :disabled="form.conditionType === ''"  class="w-40" ></el-input>-->
        </el-form-item>

        <el-form-item :label="$t('modules.data_center.dynamic_chart.order')"  >
          <div style='padding: 0 5px;'>
          <el-select v-model='form.order' class='w-40' value-key='code' clearable @change='orderChangeHandle()'>
            <el-option
              v-for='item in _orderDatas'
              :key='item.code'
              :label="$t('modules.data_center.dynamic_chart.columns.'+item.code)"
              :value='item'
            />
          </el-select>
            <el-radio-group v-model="form.orderType" class='w-50' :disabled="form.order === ''" style='padding-left: 30px'>
              <el-radio class='el-icon-bottom' label="desc">{{$t('modules.data_center.dynamic_chart.orderList.desc')}}</el-radio>
              <el-radio class='el-icon-top' label="asc">{{$t('modules.data_center.dynamic_chart.orderList.asc')}}</el-radio>
            </el-radio-group>
<!--          <el-select v-model='form.orderType' class='w-40'-->
<!--                     :disabled="form.order === ''">-->
<!--            <el-option class='el-icon-bottom' value='desc' :label="$t('modules.data_center.dynamic_chart.orderList.desc')"></el-option>-->
<!--            <el-option class='el-icon-top' value='asc' :label="$t('modules.data_center.dynamic_chart.orderList.asc')"></el-option>-->
<!--          </el-select>-->
          </div>
        </el-form-item>
      </el-form>
      <div class='chart-drawer--footer'>
        <el-button
          type='primary'
          @click='createChart'
          size='mini'
          :loading='saveLoading'
        >{{ $t('common.confirm') }}
        </el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { getDatasource, getDatasourceMode, addChartMode } from '@/api/chart'
import {
  BarIcon,
  LineIcon,
  PieIcon,
  TableIcon,
  BarIconActive,
  LineIconActive,
  PieIconActive,
  TableIconActive
} from '@/assets/images/charts'
import { preventNonNumericalInput } from '@/utils'

const initData = () => ({
  form: {
    modeName: '',
    datasourceCode: '',
    tableName: '',
    x: '',
    y: '',
    value: '',
    legend: '',
    column: '',
    conditionType: 1,
    conditionValue: 15,
    order: '', // 选中的排序值,
    orderType: '' // 升序还是降序 升序-1 降序-0
  },
  // 图标
  icons: {
    bar: BarIcon,
    line: LineIcon,
    pie: PieIcon,
    table: TableIcon,
    barActive: BarIconActive,
    lineActive: LineIconActive,
    pieActive: PieIconActive,
    tableActive: TableIconActive
  },
  orderDatas: [], // 备选的排序值,
  datasources: [],
  legendDatas: [],
  xAxisDatas: [],
  yAxisDatas: [],
  columnDatas: [],
  activeIndex: 1,
  loading: false,
  saveLoading: false,
  chartMode: {}
})

export default {
  data: function () {
    return {
      ...initData()
    }
  },
  methods: {
    preventNonNumericalInput(e) {
      return preventNonNumericalInput(e)
    },
    selectChart(index) {
      if (this.activeIndex !== index) {
        this.$data.form = initData().form
        this.activeIndex = index
        this.$refs.form.resetFields()
        this.$refs.form.clearValidate()
      }
    },
    conditionChangeHandle() {
      if (this.form.conditionType === '') {
        this.form.conditionValue = ''
      }
    },
    orderChangeHandle() {
      if (this.form.order === '') {
        this.form.orderType = ''
      }
    },
    legendChangeHandle() {
      if (this.form.legend !== '') {
        if (Array.isArray(this.form.y) && this.form.y.length > 0) {
          this.form.y = this.form.y[0]
        }
        if (Array.isArray(this.form.value) && this.form.value.length > 0) {
          this.form.value = this.form.value[0]
        }
      } else {
        if (!Array.isArray(this.form.y) && this.form.y !== '') {
          var y = []
          y.push(this.form.y)
          this.form.y = y
        }
        if (!Array.isArray(this.form.value) && this.form.value !== '') {
          var value = []
          y.push(this.form.value)
          this.form.value = value
        }
      }
    },
    createChart() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.saveLoading = true
          var chartMode = {}
          chartMode.modeName = this.form.modeName
          chartMode.tableName = this.form.tableName
          chartMode.datasourceCode = this.form.datasourceCode
          chartMode.menuCode = 'device'
          chartMode.chartType = this.chartType
          var chartModeDetailList = []
          var legend = this.form.legend
          if (legend !== '') {
            legend.dataType = 2
          }
          // 保存字段明细
          if (this.chartType === 'table') {
            chartModeDetailList = this.form.column
            console.log(chartModeDetailList)
          } else if (this.chartType === 'line' || this.chartType === 'bar') {
            chartModeDetailList.push(this.form.x)
            console.log(this.form.y)
            if (Array.isArray(this.form.y)) {
              chartModeDetailList = chartModeDetailList.concat(this.form.y)
            } else {
              chartModeDetailList.push(this.form.y)
            }

            if (legend !== '') {
              chartModeDetailList.push(legend)
            }
          } else {
            if (Array.isArray(this.form.value)) {
              chartModeDetailList = chartModeDetailList.concat(this.form.value)
            } else {
              chartModeDetailList.push(this.form.value)
            }
            console.log('chartModeDetailList:', chartModeDetailList)
            console.log('legend:', legend)
            if (legend !== '') {
              chartModeDetailList.push(legend)
            }
          }
          console.log('chartModeDetailList:', chartModeDetailList)
          // for (var i in this.chartModeDetailList) {
          //   var item = this.chartModeDetailList[i]
          //   item.name = this.$t('modules.data_center.dynamic_chart.columns.' + item.code)
          // }
          chartMode.chartModeDetailList = this.translate(chartModeDetailList)

          // 保存筛选条件
          if (
            this.form.conditionType !== undefined &&
            this.form.conditionType !== ''
          ) {
            var chartModeCondition = {}
            chartModeCondition.code = this.form.x.code
            chartModeCondition.conditionType = this.form.conditionType
            chartModeCondition.conditionValue = this.form.conditionValue
            var chartModeConditionList = []
            chartModeConditionList.push(chartModeCondition)
            chartMode.chartModeConditionList = chartModeConditionList
          }
          // 保存排序数据
          if (
            this.form.order !== undefined &&
            this.form.order !== null &&
            this.form.order !== '' &&
            this.form.order.code !== undefined
          ) {
            var chartModeOrder = {}
            console.log('order:', this.form.order)
            chartModeOrder.name = this.form.order.name
            chartModeOrder.code = this.form.order.code
            chartModeOrder.orderType = this.form.orderType
            var chartModeOrderList = []
            chartModeOrderList.push(chartModeOrder)
            chartMode.chartModeOrderList = chartModeOrderList
          }
          addChartMode(chartMode)
            .then((res) => {
              this.$message.success(this.$t('page.add_success'))
              this.handleClose()
            })
            .catch((err) => {
              this.$confirmError(err)
            })
            .finally(() => {
              this.saveLoading = false
            })
        } else {
          return false
        }
      })
    },
    fetchDataSource() {
      getDatasource().then((res) => {
        this.datasources = res
      }).catch((err) => {
          this.$confirmError(err)
        })
    },
    fetchDatasourceMode() {
      this.loading = true
      this.xAxis = {}
      getDatasourceMode({
        datasourceCode: this.form.datasourceCode
      }).then((res) => {
        this.loading = false
        this.columnDatas = res
        this.orderDatas = res
        this.legendDatas = this.xAxisDatas = res.filter(
          (data) => data.dataType === 0
        )
        this.yAxisDatas = res.filter((data) => data.dataType === 1)
      }).catch((err) => {
        this.loading = false
          this.$confirmError(err)
        })
    },
    datasourceChange() {
      Object.assign(this.form, {
        x: '',
        y: '',
        value: '',
        legend: '',
        column: '',
        conditionType: 1,
        conditionValue: 15,
        order: '', // 选中的排序值,
        orderType: '' // 升序还是降序 升序-1 降序-0
      })
      this.fetchDatasourceMode()
      for (var i in this.datasources) {
        if (this.datasources[i].datasourceCode === this.form.datasourceCode) {
          this.form.tableName = this.datasources[i].tableName
        }
      }
      this.yAxiss = []
    },
    initOptions() {
      this.orderDatas = []
      this.legendDatas = []
      this.xAxisDatas = []
      this.yAxisDatas = []
      this.columnDatas = []
      this.activeIndex = 1
      this.loading = false
    },
    handleClose() {
      this.$data.form = initData().form
      this.initOptions()
      this.activeIndex = 1
      this.$refs.form.resetFields()
      this.$refs.form.clearValidate()
      this.$emit('confirm', this.title)
    },
    translate(list) {
      return list.map((data) => {
        return {
          ...data,
          name: this.$t(
            'modules.data_center.dynamic_chart.columns.' + data.code
          )
        }
      })
    }
  },
  computed: {
    rules() {
      const rules = {
        modeName: [
          {
            required: true,
            message: this.$t(
              'modules.data_center.dynamic_chart.message.mode_name_null'
            ),
            trigger: 'blur'
          }
        ],
        datasourceCode: [
          {
            required: true,
            message: this.$t(
              'modules.data_center.dynamic_chart.message.datasource_null'
            ),
            trigger: 'blur'
          }
        ],
        x: [
          {
            required: true,
            message: this.$t(
              'modules.data_center.dynamic_chart.message.x_null'
            ),
            trigger: 'blur'
          }
        ],
        y: [
          {
            required: true,
            message: this.$t(
              'modules.data_center.dynamic_chart.message.y_null'
            ),
            trigger: 'blur'
          }
        ],
        value: [
          {
            required: true,
            message: this.$t(
              'modules.data_center.dynamic_chart.message.value_null'
            ),
            trigger: 'blur'
          }
        ],
        column: [
          {
            required: true,
            message: this.$t(
              'modules.data_center.dynamic_chart.message.value_null'
            ),
            trigger: 'blur'
          }
        ]
      }
      return rules
    },
    chartType() {
      if (this.activeIndex === 1) return 'bar'
      else if (this.activeIndex === 2) return 'line'
      else if (this.activeIndex === 3) {
        return 'pie'
      } else if (this.activeIndex === 4) {
        return 'table'
      } else {
        return ''
      }
    },
    _xAxisDatas() {
      return this.xAxisDatas.map((data) => {
        if (data.code === this.form.legend.code) {
          return { ...data, disabled: true }
        }
        return data
      })
    },
    _legendDatas() {
      return this.legendDatas.map((data) => {
        if (this.form.x !== null && data.code === this.form.x.code) {
          return { ...data, disabled: true }
        }
        return data
      })
    },

    _orderDatas() {
      var orderList = []
      if (this.form.x !== '') {
        orderList.push(this.form.x)
      }
      if (this.form.legend !== '') {
        orderList.push(this.form.legend)
      }
      if (Array.isArray(this.form.y) && this.form.y.length > 0) {
        orderList = orderList.concat(this.form.y)
      }
      if (!Array.isArray(this.form.y) && this.form.y !== '') {
        orderList.push(this.form.y)
      }
      if (Array.isArray(this.form.value) && this.form.value.length > 0) {
        orderList = orderList.concat(this.form.value)
      }
      if (!Array.isArray(this.form.value) && this.form.value !== '') {
        orderList.push(this.form.value)
      }
      if (this.form.column !== null && this.form.column.length > 0) {
        orderList = orderList.concat(this.form.column)
      }
      return orderList
    }
  },
  mounted() {
    this.fetchDataSource()
  }
}
</script>

<style lang='scss'>
.chart-drawer {
  .el-form--label-top .el-form-item__label {
    padding: 0;
  }

  .el-select,
  .el-checkbox,
  .el-input {
    width: 100%;

    &.w-40 {
      width: 40%;
    }
  }

  .el-select + .el-input,
  .el-select + .el-select {
    margin-left: 10px;
  }

  .el-form-item {
    margin-bottom: 10px;
  }
}
</style>

<style lang='scss' scoped>
.chart-drawer {
  padding: 0 20px;
}

.chart-drawer--footer {
  text-align: right;
  padding: 20px 0;
}

.chart-icons {
  margin-bottom: 20px;

  img {
    cursor: pointer;
    width: 48px;
    margin: 0 10px;
    padding: 4px;
    /* border: 1px solid transparent; */

    &:hover {
      border-color: #cccccc;
    }

    &.selected {
      background-color: #226abc;
      border-radius: 4px;
      /* border-color: #000000; */
    }
  }
}
</style>
